﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BIS.Portal.Core.Base;
using BIS.Portal.Core.Global;
using BIS.Portal.Modules.CMS.BO;
using BIS.Portal.Modules.CMS.Entity;
using BIS.Utility.Converter;
using BIS.Portal.Core.Entity;


namespace BIS.Portal.Modules.CMS.Adm
{
    public partial class AdminCmsCategoryControl : ControlBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            BindingData();
            visibleButton();
            tvCategory.ExpandAll();
            itemDataForDdlDanhMucCha();
            BindListOfLanguageAlias();
            BindListOfPageAliasNhomNoiDung();
            BindListOfPageAliasNoiDung();
        }
        private void BindListOfPageAliasNhomNoiDung()
        {
            Dictionary<string, FullPageSiteEntity> listOfPage = new Dictionary<string, FullPageSiteEntity>();
            PortalContext.GetPageList(0, ref listOfPage, "", false);

            if (listOfPage != null)
            {
                ddlPageAliasNhomNoiDung.Items.Clear();
                foreach (KeyValuePair<string, FullPageSiteEntity> page in listOfPage)
                {
                    if (page.Value.PageAlias != PortalContext.PageAlias && page.Key != null && page.Value != null)
                    {
                        ddlPageAliasNhomNoiDung.Items.Add(new ListItem(page.Key, page.Value.PageAlias));
                    }
                }
            }
        }
        private void BindListOfPageAliasNoiDung()
        {
            Dictionary<string, FullPageSiteEntity> listOfPage = new Dictionary<string, FullPageSiteEntity>();
            PortalContext.GetPageList(0, ref listOfPage, "", false);

            if (listOfPage != null)
            {
                ddlPageAliasNoiDung.Items.Clear();
                foreach (KeyValuePair<string, FullPageSiteEntity> page in listOfPage)
                {
                    if (page.Value.PageAlias != PortalContext.PageAlias && page.Key != null && page.Value != null)
                    {
                        ddlPageAliasNoiDung.Items.Add(new ListItem(page.Key, page.Value.PageAlias));
                        //Response.Write(page.Value.PageAlias+"</br>");
                    }
                }
            }
        }
        private void BindListOfLanguageAlias()
        {
            IList<FullSiteLanguageEntity> lstLang = PortalContext.Languages;
            ddlNgonNgu.DataSource = lstLang;
            ddlNgonNgu.DataTextField = "DisplayName";
            ddlNgonNgu.DataValueField = "LanguageInUseId";
            ddlNgonNgu.DataBind();
        }
        private void itemDataForDdlDanhMucCha()
        {
            ddlDanhMucCha.Items.Clear();
            IList<AdminCmsCategoryNameEntity> list = AdminCmsCategoryBO.GetCategoryNameForParentCateId(1);
            ListItem rootItem = new ListItem("----Không chọn---", "0");
            ddlDanhMucCha.Items.Add(rootItem);
            load_danhmuc(0, "", list);
        }
        #region Ẩn button
        private void visibleButton()
            {
            ibtnAddCategory.Enabled = true;
            btnCapNhat.Visible = false;
            btnBoQua.Visible = false;
            btnThemMoi.Visible = true;
            }
         #endregion
        #region BinData Category vào TreeView
        private void BindingData()
        {
            tvCategory.Nodes.Clear();
            tvCategory.RootNodeStyle.ImageUrl = "Images/root.png";
            // lay het data ve
            IList<AdminCmsCategoryEntity> listCategory = AdminCmsCategoryBO.GetByLanguageInUseId(1);
            TreeNode treeNode = new TreeNode();
            ParseListCategory(listCategory, ref treeNode, 0);
            tvCategory.Nodes.Add(treeNode);
            tvCategory.Nodes[0].Text = "<span class='TextRootNode'>CMS Category</span>";
            tvCategory.Nodes[0].Value = "0";
        }
        #endregion
        #region De qui load dada from Sql to TreeView
        private void ParseListCategory(IList<AdminCmsCategoryEntity> listCate,
                                        ref TreeNode treeNode,
                                        int parentId)
        {
            for (int i = 0; i < listCate.Count; i++)
            {
                if (listCate[i].Parent_category_id == parentId)
                {
                    TreeNode tempNode = new TreeNode(listCate[i].Category_name, listCate[i].Category_id.ToString());
                    treeNode.ChildNodes.Add(tempNode);
                    TreeNode childNode = treeNode.ChildNodes[treeNode.ChildNodes.Count - 1];

                    #region Icon TreeNode theo Category_type
                    if (listCate[i].Category_type == 1)
                    {
                        tempNode.ImageUrl = ModulePath + "Images/list_article.gif";

                    }
                    else if (listCate[i].Category_type == 2)
                    {
                        tempNode.ImageUrl = ModulePath + "Images/single_article.gif";
                    }
                    else if (listCate[i].Category_type == 3)
                    {
                        tempNode.ImageUrl = ModulePath + "Images/gallery.gif";
                    }
                    #endregion
                    #region Icon TreeNode theo Use_direct_url
                    if (listCate[i].Category_type == 1 && listCate[i].Use_direct_url == 1)
                    {
                        tempNode.ImageUrl = ModulePath + "Images/direct_link.jpg";
                    }
                    else if (listCate[i].Category_type == 2 && listCate[i].Use_direct_url == 1)
                    {
                        tempNode.ImageUrl = ModulePath + "Images/direct_link.jpg";
                    }
                    else if (listCate[i].Category_type == 3 && listCate[i].Use_direct_url == 1)
                    {
                        tempNode.ImageUrl = ModulePath + "Images/direct_link.jpg";
                    }
                    #endregion
                    #region Text Status
                    if (listCate[i].Status == 99)
                    {
                        tempNode.Text = "<span class='deactived'>" + listCate[i].Category_name + "</span>";
                    }
                    else if (listCate[i].Status == 1)
                    {
                        tempNode.Text = "<span class='available'>" + listCate[i].Category_name + "</span>";
                    }
                    else if (listCate[i].Status == 0)
                    {
                        tempNode.Text = "<span class='logic-delete'>" + listCate[i].Category_name + "</span>";
                    }
                    #endregion
                    #region Text Status Show_in_menu
                    if (listCate[i].Status == 99 && listCate[i].Show_in_menu == 0)
                    {
                        tempNode.Text = "<span class='hidden'>" + listCate[i].Category_name + "</span>";
                    }
                    else if (listCate[i].Status == 1 && listCate[i].Show_in_menu == 0)
                    {
                        tempNode.Text = "<span class='hidden'>" + listCate[i].Category_name + "</span>";
                    }
                    else if (listCate[i].Status == 0 && listCate[i].Show_in_menu == 0)
                    {
                        tempNode.Text = "<span class='hidden'>" + listCate[i].Category_name + "</span>";
                    }
                    #endregion
                    ParseListCategory(listCate, ref childNode, listCate[i].Category_id);
                }
            }
        }
        #endregion
        #region Load thành phần from
        private void load_danhmuc(int parent_id, string sSeparator, IList<AdminCmsCategoryNameEntity> list)
        {
            for (int i = 0; i < list.Count; i++)
            {
                if (list[i].Parent_Category_id == parent_id)
                {
                    ListItem item = new ListItem(sSeparator + list[i].Category_name, Functions.GetString(list[i].Category_id));
                    ddlDanhMucCha.Items.Add(item);
                    load_danhmuc(list[i].Category_id, "---" + sSeparator, list);
                }
            }
        }
        #endregion
        #region Data chi tiết của Category khi selectedChange TreeView
        protected void tvCategory_SelectedNodeChanged(object sender, EventArgs e)
        {
            if (tvCategory.SelectedValue != "0")
            {
                btnCapNhat.Visible = true;
                btnCapNhat.Enabled = true;
                btnBoQua.Visible = true;
                btnBoQua.Enabled = true;
                btnThemMoi.Visible = false;
                string cateId = tvCategory.SelectedValue;
                getDataTreeNode(Functions.GetInt(cateId));
                ltrMessage.Text = "";
            }
        }
        private void getDataTreeNode(int cateID)
        {
            Dictionary<string, FullPageSiteEntity> listOfPage = new Dictionary<string, FullPageSiteEntity>();
            PortalContext.GetPageList(0, ref listOfPage, "", false);
            //AdminCmsCategoryEntity objCate = AdminCmsCategoryBO.GetByCateId(cateID, PortalContext.LanguageInUseId);
            AdminCmsCategoryEntity objCate = AdminCmsCategoryBO.GetByCateId(cateID, 1);
            int temp;
            itemDataForDdlDanhMucCha();
            hdfCateId.Value = Functions.GetString(objCate.Category_id);
            txtTenNhomNoiDung.Text = objCate.Category_name;
            txtMoTa.Text = objCate.Category_description;
            txtTieuDeMeta.Text = objCate.Category_meta_title;
            txtMoTaMeta.Text = objCate.Category_meta_description;
            txtTuKhoaMeta.Text = objCate.Category_meta_keyword;
            txtLienKetTrucTiep.Text = objCate.Category_direct_url;
            temp = objCate.Use_direct_url;
            if (temp == 1)
            {
                chkSuDungLienKetTrucTiep.Checked = true;
            }
            else
            {
                chkSuDungLienKetTrucTiep.Checked = false;
            }
            temp = objCate.Show_in_menu;
            if (temp == 1)
            {
                chkChoPhepHienThiDuLieu.Checked = true;
            }
            else
            {
                chkChoPhepHienThiDuLieu.Checked = false;
            }

            ddlDanhMucCha.SelectedValue = Functions.GetString(objCate.Parent_category_id);
            ddlLoaiNhomNoiDung.SelectedValue = Functions.GetString(objCate.Category_type);
            ddlNgonNgu.SelectedValue = Functions.GetString(objCate.Language_in_use_id);
            ddlTrangThai.SelectedValue = Functions.GetString(objCate.Status);
            //Fill dữ liệu vào dropdownlist ddlPageAliasNhomNoiDung
            ListItem findvalueddl1 = ddlPageAliasNhomNoiDung.Items.FindByValue(objCate.Category_page_alias);
            if (findvalueddl1 != null)
            {
                if (findvalueddl1.Value == objCate.Category_page_alias)
                {
                    ddlPageAliasNhomNoiDung.SelectedValue = objCate.Category_page_alias;
                }
            }
            else
            {

                ddlPageAliasNhomNoiDung.SelectedIndex =0;
            }
            //Fill dữ liệu vào dropdownlist ddlPageAliasNoiDung
            ListItem findvalueddl2 = ddlPageAliasNoiDung.Items.FindByValue(objCate.Article_page_alias);
            if (findvalueddl2 != null)
            {
                if (findvalueddl2.Value == objCate.Article_page_alias)
                {
                    ddlPageAliasNoiDung.SelectedValue = objCate.Article_page_alias;
                }
            }
            else
            {
                ddlPageAliasNoiDung.SelectedIndex = 0;
            }
            // disable item dang chon trong danh muc cha
            for (int i = 0; i < ddlDanhMucCha.Items.Count; i++)
            {
                if (ddlDanhMucCha.Items[i].Value.Equals(objCate.Category_id.ToString()))
                {
                    ddlDanhMucCha.Items[i].Attributes.Add("disabled", "disabled");
                    break;
                }
            }
        }

        #endregion
        private void boqua()
        {
            txtTenNhomNoiDung.Text = "";
            txtMoTa.Text = "";
            txtTieuDeMeta.Text = "";
            txtMoTaMeta.Text = "";
            txtTuKhoaMeta.Text = "";
            txtLienKetTrucTiep.Text = "";
            chkChoPhepHienThiDuLieu.Checked = false;
            chkSuDungLienKetTrucTiep.Checked = false;
            btnCapNhat.Visible = false;
            btnBoQua.Enabled = false;
            btnThemMoi.Visible = true;
            ibtnAddCategory.Enabled = true;
            ddlLoaiNhomNoiDung.SelectedIndex = 0;
            ddlTrangThai.SelectedIndex = 0;
            ddlPageAliasNhomNoiDung.SelectedIndex = 0;
            ddlPageAliasNoiDung.SelectedIndex = 0;
            ddlDanhMucCha.SelectedIndex = 0;
        }

        protected void btnBoQua_Click(object sender, EventArgs e)
        {
            BindingData();
            boqua();
            tvCategory.ExpandAll();
        }
        #region Add Category
        protected void btnThemMoi_Click(object sender, EventArgs e)
        {
            
            if (Page.IsValid)
            {
                AdminCmsCategoryEntity cateEntityInsert = new AdminCmsCategoryEntity();
                getDataForm(ref cateEntityInsert);
                AdminCmsCategoryBO.AddCategory(cateEntityInsert);
                BindingData();
                tvCategory.ExpandAll();
                itemDataForDdlDanhMucCha();
                boqua();
            }
        }
        protected void ibtnAddCategory_Click(object sender, ImageClickEventArgs e)
        {
            BindingData();
            boqua();
            tvCategory.ExpandAll();
        }
        private void getDataForm(ref AdminCmsCategoryEntity cateEntity)
        {
            cateEntity.Category_id = Functions.GetInt(hdfCateId.Value);
            cateEntity.Category_page_alias = ddlPageAliasNhomNoiDung.SelectedValue;
            cateEntity.Article_page_alias = ddlPageAliasNoiDung.SelectedValue;
            cateEntity.Category_name = txtTenNhomNoiDung.Text;
            cateEntity.Category_description = txtMoTa.Text;
            cateEntity.Category_meta_title = txtTieuDeMeta.Text;
            cateEntity.Category_meta_description = txtMoTaMeta.Text;
            cateEntity.Category_meta_keyword = txtTuKhoaMeta.Text;
            cateEntity.Parent_category_id = Functions.GetInt(ddlDanhMucCha.SelectedValue);
            cateEntity.Show_in_menu = chkChoPhepHienThiDuLieu.Checked ? 1 : 0;
            cateEntity.Category_direct_url = txtLienKetTrucTiep.Text;
            cateEntity.Category_type = Functions.GetInt(ddlLoaiNhomNoiDung.SelectedValue);
            cateEntity.Use_direct_url = chkSuDungLienKetTrucTiep.Checked ? 1 : 0;
            cateEntity.Language_in_use_id = int.Parse(ddlNgonNgu.SelectedValue);
            cateEntity.Status = int.Parse(ddlTrangThai.SelectedValue);
            cateEntity.Last_update = DateTime.Now;
            //cateEntity.Last_update_by = PortalContext.CurrentUser.UserName;
            cateEntity.Last_update_by = "Tungnt1";
            cateEntity.Priority = 0;
        }   
        #endregion
        #region Cập nhật dữ liệu
        protected void btnCapNhat_Click(object sender, EventArgs e)
        {
            AdminCmsCategoryEntity cateEntity = new AdminCmsCategoryEntity();
            getDataForm(ref cateEntity);
            AdminCmsCategoryBO.UpdateCategory(cateEntity);
            if (AdminCmsCategoryBO.UpdateCategory(cateEntity))
            {
                ShowMessage("Cập nhật thông tin danh mục thành công !", false);
            }
            else
            {
                ShowMessage("Cập nhật thông tin danh mục thất bại !", true);
            }
            boqua();
            BindingData();
            tvCategory.ExpandAll();
            itemDataForDdlDanhMucCha();
        }
        #endregion

        #region Delete Category
        protected void ibtnDeleteCategory_Click(object sender, ImageClickEventArgs e)
        {
            string cateId = tvCategory.SelectedValue;
            int numOfChild = 0;
            AdminCmsCategoryBO.CheckParentForDeleteCate(Functions.GetInt(cateId), ref numOfChild);
            if (numOfChild > 0)
            {
                ShowMessage("Không thể xóa nội dung này vì bên trong còn có nội dung con", true);
            }
            else
            {
                AdminCmsCategoryBO.DeleteCategory(Functions.GetInt(cateId));
            }

            boqua();
            BindingData();
            tvCategory.ExpandAll();
            itemDataForDdlDanhMucCha();
        }

        #endregion

        protected void ibtnRedirect_Click(object sender, ImageClickEventArgs e)
        {
            string pageAlias =
                GetControlSetting<string>(
                    ModuleSettingNames.AdminCmsCategoryControl.AdminCmsCategory_SelectedAliasPage,
                    PortalContext.LanguageAlias);

            string url = WebHelpers.GetLink(UrlRewriteRules.URLListOfArticle, pageAlias,
                                            new string[] { QueryStringKeys.CategoryId }, new string[] { tvCategory.SelectedValue });
            Response.Redirect(url);

        }
        private void ShowMessage(string message, bool isErr)
        {
            string p = "<p style='color:{0}'>{1}</p>";

            ltrMessage.Text = string.Format(p, isErr ? "red" : "blue", message);
        }

       

    }
}